
TARGET=led

BUILD_DIR=output

##### gcc
CROSS_COMPILE ?=arm-none-eabi-

CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
ld=$(CROSS_COMPILE)ld
OD=$(CROSS_COMPILE)objdump
#### src files
#SRC_C=$(wildcard Src/*.c Drivers/STM32F1xx_HAL_Driver/Src/*.c)
#SRC_C=Src/main.c Src/Src/stm32f1xx_it.c 
SRC_S=Src/startup_stm32f103xb.s

SRC_C+=$(wildcard Src/*.c)
SRC_C+=$(wildcard freertos/*.c)

SRC_ld=link.ld

#### .o files
OBJ_C=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJ_s=$(BUILD_DIR)/startup_stm32f103xb.o

#### include dir
INC=-IInc \
-ICMSIS/Device/ST/STM32F1xx/Include \
-ICMSIS/Include \
-Ifreertos/include

#### CFLAGS
DEFS=\
#-DUSE_HAL_DRIVER \
#-DSTM32F103xB
 
CFLAGS= \
-mcpu=cortex-m3 \
-mthumb \
$(DEFS) \
-Wall \
-fdata-sections \
-ffunction-sections \
#-Og \
#-Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst))
#-g \
#-gdwarf-2 \
#-MMD -MP -MF"$(@:%.o=%.d)"

#### LINK 

LIBS=\
#-lc -lm

#如果程序并不实际使用系统函数，但是某些代码引用了系统函数，那么可以引入libnosys，以便通过编译。
#LIBS+=-lnosys
LDFLAGS =\
-mcpu=cortex-m3 \
-Wl,--gc-sections

#LDFLAGS +=-specs=nano.specs \

LDFLAGS +=\
-T$(SRC_ld) \
$(LIBS)

LDFLAGS += -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref

ELF =$(BUILD_DIR)/$(TARGET).elf
BIN =$(BUILD_DIR)/$(TARGET).bin
DIS =$(BUILD_DIR)/$(TARGET).dis

### .c path set
vpath %.c $(sort $(dir $(SRC_C) ))

 
#### build
.PHONY:all clean  test dis

all: $(BUILD_DIR) $(ELF) $(BIN) $(DIS)
	@echo all

# mkdir 
$(BUILD_DIR):
	mkdir $@

# link elf
$(ELF):$(OBJ_C) $(OBJ_s)
	@echo  abc
	$(CC) $(OBJ_C) $(OBJ_s) $(LDFLAGS) -o $@
	$(SZ) $@

# .c -> .o
$(BUILD_DIR)/%.o : %.c
	$(CC) -c $(CFLAGS)  $< $(INC) -o $@
	

# .s -> .o
$(OBJ_s):$(SRC_S)
	$(AS) -c $(CFLAGS) $< $(INC) -o $@

# .elf -> .bin
$(BIN):$(ELF)
	$(CP) -O binary -S $< $@

dis: $(DIS)
#make 使用tools中的make工具，msys的make报错 'no such file'
$(DIS):$(ELF)
	@echo objdump    
	$(OD) -DhSdg $< > $@

clean:
	rm -rf $(BUILD_DIR)

test:
#	@echo $(SRC_C) 
	@echo $(OBJ_C)  


#-include $(wildcard $(BUILD_DIR)/*.d)